package com.example.school.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.school.entity.Student;
import com.example.school.service.IStudentService;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/student")//区分模块
public class StudentController {
    @Resource
    private IStudentService studentService;


    @GetMapping("/list")
    public List<Student> list(String name){
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(name),"name", name);
        return studentService.list(queryWrapper);
    }

    @GetMapping("/getById")
    public Student getById(Integer id){
        return studentService.getById(id);
    }

    @PostMapping("/add")
    //@Validated验证->参数BindingResult(封装错误信息的)
    /*
     *@RequestBody是springMVC提供的,用于接收请求体中的参数,SpringMVC会将请求体中JSON格式的参数自动转换为java
     *中的对象
    */
    public String add(@RequestBody @Validated Student student, BindingResult br){
        if (br.hasErrors()){
            return br.getFieldError().getDefaultMessage();//得到具体错误信息
        }
        studentService.save(student);
        return "OK";
    }

    @PostMapping("/delete")
    public String deleteById(Integer id){
        studentService.removeById(id);
        return "OK";
    }

    @PostMapping("/update")
    public String updateById(@RequestBody @Validated Student student,BindingResult br){
        if (br.hasErrors()){
            return br.getFieldError().getDefaultMessage();//得到具体错误信息
        }
        studentService.updateById(student);
        return "OK";
    }


}
